<script setup>
import {onMounted, ref} from "vue";
import {useUserStore} from "@/stores/userStore.js";
import {ElMessage, ElMessageBox} from 'element-plus';
import UserEdit from "@/views/system/UserEdit.vue";

const userStore = useUserStore();

const tableData = ref([]);
const searchForm = ref({
  username: '',
  email: '',
  mobile: ''
});

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const editDialogVisible = ref(false);
const currentUser = ref({});

const fetchData = async () => {
  try {
    loading.value = true;
    const res = await userStore.getUserList({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.value.username,
      email: searchForm.value.email,
      mobile: searchForm.value.mobile
    });

    tableData.value = userStore.userList;
    total.value = userStore.pageInfo.total;

  } catch (error) {
    ElMessage.error('获取用户列表失败: ' + error.message);
    console.error('API Error:', error);
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

const handleCurrentChange = (val) => {
  console.log('currentPage:', val);
  currentPage.value = val;
  fetchData();
};

const resetSearch = () => {
  searchForm.value = {username: '', email: '', mobile: ''};
  currentPage.value = 1;
  fetchData();
};

// 编辑用户
const handleEdit = (row) => {
  currentUser.value = {...row};
  editDialogVisible.value = true;
};

// 逻辑删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除用户 ${row.username} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await userStore.deleteUser(row.id);
          ElMessage.success('删除成功');
          await fetchData();
        } catch (error) {
          ElMessage.error('删除失败: ' + (error.message || '未知错误'));
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

// 编辑成功后回调
const handleUpdateSuccess = () => {
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="user-management-container">
    <el-card shadow="hover" class="search-card">
      <div class="search-header">
        <h3>用户查询</h3>
        <div class="search-actions">
          <el-button type="primary" @click="fetchData" :loading="loading">
            <el-icon class="el-icon--left">
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon class="el-icon--left">
              <Refresh/>
            </el-icon>
            重置
          </el-button>
        </div>
      </div>

      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱">
              <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号">
              <el-input v-model="searchForm.mobile" placeholder="请输入手机号" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="hover" class="table-card">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
          stripe
          border
          highlight-current-row
      >
        <el-table-column label="ID" prop="id" width="80" align="center"/>
        <el-table-column label="账号" prop="username" width="120"/>
        <el-table-column label="密码" prop="password" width="200">
          <template #default="{row}">
            <el-text truncated>{{ row.password }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="email" width="180"/>
        <el-table-column label="手机号" prop="mobile" width="150"/>
        <el-table-column label="状态" prop="isDelete" width="100" align="center"/>
        <el-table-column label="用户类型" prop="userType" width="180" align="center"/>
        <el-table-column label="部门ID" prop="deptId" width="180" align="center"/>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <!-- 添加了 @click="handleEdit(scope.row)" 事件 -->
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                <span class="btn-text">编辑</span>
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                <span class="btn-text">删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 编辑用户对话框 -->
    <UserEdit
        v-model:visible="editDialogVisible"
        :user-data="currentUser"
        @success="handleUpdateSuccess"
    />
  </div>
</template>

<style scoped>
.user-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 18px;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.btn-text {
  display: inline-block;
  width: 100%;
  text-align: center;
}

.el-button {
  padding: 8px 15px;
}

.el-text {
  display: inline-block;
  max-width: 180px;
}
</style>
